package com.mine.modules.vm.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mine.common.config.exception.MineBootException;
import com.mine.common.domain.vo.Result;
import com.mine.modules.vm.common.constant.BizConstant;
import com.mine.modules.vm.domain.query.ActionByLayerQuery;
import com.mine.modules.vm.domain.query.LayerActionQuery;
import com.mine.modules.vm.entity.VmLayer;
import com.mine.modules.vm.entity.VmLayerAction;
import com.mine.modules.vm.entity.VmLayerActionInfo;
import com.mine.modules.vm.mapper.VmLayerActionMapper;
import com.mine.modules.vm.service.IVmLayerActionInfoService;
import com.mine.modules.vm.service.IVmLayerActionService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 场景菜单 服务实现类
 * </p>
 *
 * @author xujf
 * @since 2024-10-21
 */
@Service
@RequiredArgsConstructor
public class VmLayerActionServiceImpl extends ServiceImpl<VmLayerActionMapper, VmLayerAction> implements IVmLayerActionService {

    private final IVmLayerActionInfoService vmLayerActionInfoService;

    @Override
    public Result<?> actionList(LayerActionQuery layerActionQuery) {
        LambdaQueryWrapper<VmLayerAction> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(layerActionQuery.getLayerId()), VmLayerAction::getLayerId, layerActionQuery.getLayerId());
        queryWrapper.eq(StringUtils.isNotBlank(layerActionQuery.getActionType()), VmLayerAction::getActionType, layerActionQuery.getActionType());
        queryWrapper.and(StringUtils.isNotBlank(layerActionQuery.getKeywords()), e -> e
                .like(VmLayerAction::getActionCode, layerActionQuery.getKeywords())
                .or()
                .like(VmLayerAction::getActionName, layerActionQuery.getKeywords())
        );
        queryWrapper.orderByAsc(VmLayerAction::getSortOrder);
        Page<VmLayerAction> page = new Page<>(layerActionQuery.getPageNo(), layerActionQuery.getPageSize());
        IPage<VmLayerAction> pageList = this.page(page, queryWrapper);
        return Result.OK("查询成功！", pageList);
    }

    @Override
    public Result<?> actionInfoList(String actionId, String keywords) {
        if (StringUtils.isEmpty(actionId)) {
            return Result.error("参数不完整！");
        }
        return Result.OK("查询成功！", vmLayerActionInfoService.lambdaQuery()
                .eq(VmLayerActionInfo::getActionId, actionId)
                .and(StringUtils.isNotBlank(keywords), e -> e
                        .like(VmLayerActionInfo::getOpenCode, keywords)
                        .or()
                        .like(VmLayerActionInfo::getOpenName, keywords)
                        .or()
                        .like(VmLayerActionInfo::getCloseCode, keywords)
                        .or()
                        .like(VmLayerActionInfo::getCloseName, keywords)
                )
                .orderByAsc(VmLayerActionInfo::getSortOrder)
                .list());
    }

    @Override
    public Result<?> addOrEditAction(VmLayerAction vmLayerAction) {
        if (vmLayerAction == null || StringUtils.isEmpty(vmLayerAction.getLayerId())
                || StringUtils.isEmpty(vmLayerAction.getActionType())) {
            return Result.error("参数不完整！");
        }
        if (StringUtils.isEmpty(vmLayerAction.getId())) {
            if (StringUtils.isEmpty(vmLayerAction.getActionType())) {
                vmLayerAction.setActionType(BizConstant.LAYER_ACTION_TYPE_BUTTON);
            }
            if (this.save(vmLayerAction)) {
                return Result.ok("添加成功！");
            } else {
                return Result.error("保存失败！");
            }
        } else {
            VmLayerAction old = this.getById(vmLayerAction.getId());
            if (old == null) {
                return Result.error("数据不存在，请刷新重试！");
            }
            if (this.updateById(vmLayerAction)) {
                return Result.ok("修改成功！");
            } else {
                return Result.error("修改失败！");
            }
        }
    }

    @Override
    public Result<?> addOrEditActionInfo(VmLayerActionInfo vmLayerActionInfo) {
        if (vmLayerActionInfo == null || StringUtils.isEmpty(vmLayerActionInfo.getActionId())) {
            return Result.error("参数不完整！");
        }
        VmLayerAction vmLayerAction = this.getById(vmLayerActionInfo.getActionId());
        if (vmLayerAction == null) {
            return Result.error("操作不存在！");
        }
        if (StringUtils.isEmpty(vmLayerActionInfo.getId())) {
            vmLayerActionInfo.setLayerId(vmLayerAction.getLayerId());
            if (this.vmLayerActionInfoService.save(vmLayerActionInfo)) {
                return Result.ok("添加成功！");
            } else {
                return Result.error("保存失败！");
            }
        } else {
            VmLayerActionInfo old = this.vmLayerActionInfoService.getById(vmLayerActionInfo.getId());
            if (old == null) {
                return Result.error("数据不存在，请刷新重试！");
            }
            if (this.vmLayerActionInfoService.updateById(vmLayerActionInfo)) {
                return Result.ok("修改成功！");
            } else {
                return Result.error("修改失败！");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteAction(String id) {
        VmLayerAction vmLayerAction = this.getById(id);
        if (vmLayerAction == null) {
            return Result.error("数据不存在，请刷新重试！");
        }
        this.removeById(id);
        //删除子表
        this.vmLayerActionInfoService.remove(
                new LambdaQueryWrapper<>(VmLayerActionInfo.class)
                        .eq(VmLayerActionInfo::getActionId, id)
        );
        return Result.ok("删除成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatchAction(String ids) {
        try {
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (StringUtils.isNotEmpty(id)) {
                    try {
                        this.deleteAction(id);
                    } catch (MineBootException e) {
                        log.warn(e.getMessage());
                        throw e;
                    }
                }
            }
            return Result.OK("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("删除失败!");
        }
    }

    @Override
    public Result<?> deleteActionInfo(String id) {
        VmLayerActionInfo vmLayerActionInfo = this.vmLayerActionInfoService.getById(id);
        if (vmLayerActionInfo == null) {
            return Result.error("数据不存在，请刷新重试！");
        }
        this.vmLayerActionInfoService.removeById(id);
        return Result.ok("删除成功！");
    }

    @Override
    public Result<?> deleteBatchActionInfo(String ids) {
        try {
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (StringUtils.isNotEmpty(id)) {
                    try {
                        this.deleteActionInfo(id);
                    } catch (MineBootException e) {
                        log.warn(e.getMessage());
                        throw e;
                    }
                }
            }
            return Result.OK("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("删除失败!");
        }
    }

    @Override
    public Result<?> getActionByLayerId(ActionByLayerQuery query) {
        return Result.OK(
                this.lambdaQuery()
                        .eq(VmLayerAction::getLayerId, query.getLayerId())
                        .eq(StringUtils.isNotBlank(query.getActionType()), VmLayerAction::getActionType, query.getActionType())
                        .orderByAsc(VmLayerAction::getSortOrder)
                        .list()
                        .stream()
                        .peek(e -> e.setActionInfos(
                                        this.vmLayerActionInfoService
                                                .lambdaQuery()
                                                .eq(VmLayerActionInfo::getActionId, e.getId())
                                                .orderByAsc(VmLayerActionInfo::getSortOrder)
                                                .list()
                                )
                        ).collect(Collectors.toList())
        );
    }

    @Override
    public void copyActionByLayerId(String layerId, String targetLayerId) {
        List<VmLayerAction> actions = this.lambdaQuery().eq(VmLayerAction::getLayerId, layerId).list();
        for (VmLayerAction action : actions) {
            String newId = UUID.randomUUID().toString();
            List<VmLayerActionInfo> infos = this.vmLayerActionInfoService.lambdaQuery().eq(VmLayerActionInfo::getActionId, action.getId()).list();
            action.setId(newId);
            action.setLayerId(targetLayerId);
            if(this.save(action)){
                for (VmLayerActionInfo info : infos) {
                    info.setId(UUID.randomUUID().toString());
                    info.setActionId(newId);
                    this.vmLayerActionInfoService.save(info);
                }
            }
        }
    }
}
